
import clasnames from 'classnames';
import { camelCaseObject } from '../../util/typeUtil';
import _ from 'lodash';
import { CellProps } from './ModeExcel';

interface TabCellProps {
    name: string;
    height: number | string;
    defaultActiveKey: string;
    tabs: {
        key: string;
        name: string;
        tab: string;
    }[];
}

export const parseCell = (cell: any = {}, rowHeight?: number, colAttrs: any = {}): CellProps => {
    let rt = {} as CellProps;

    const { colspan, rowspan, id, font = {}, eborder = [], format, etype, evalue, field, fieldtype, financial, attrs = {}, detail, tab = {} ,stylejson} = cell;
    const ids = id.split(',') as string[];
    rt.row = parseInt(ids[0]);
    if (ids.length == 2) {
        rt.col = parseInt(ids[1]);
    }

    //单元格边框
    let borderStyle = appendBorder(eborder, etype);
    let { style, innerStyle } = appendStyle(etype, cell);
    //财务格式所在单元格div增加高度100%
    if (financial) {
        style.lineHeight = rowHeight + 'px';
        style.height = rowHeight;
        innerStyle.height = '100%';
        innerStyle.display = 'flex';
        if (font['text-align']) {
            switch(font['text-align']){
                case "right":innerStyle.justifyContent="flex-end";break;
                case "center":innerStyle.justifyContent="center";break;
                default:innerStyle.justifyContent="flex-start";
            }
        } else {
            innerStyle.justifyContent="flex-start";
        }
        if (font['vertical-align']) {
            switch(font['vertical-align']){
                case "bottom":innerStyle.alignItems="flex-end";break;
                case "middle":innerStyle.alignItems="center";break;
                case "top":innerStyle.alignItems="flex-start";break;

            }
        } else {
            innerStyle.alignItems =  'flex-start'
        }
        if (font['valign']) {
            switch(font['valign']){
                case "bottom":innerStyle.alignItems="flex-end";break;
                case "middle":innerStyle.alignItems="center";break;
                case "top":innerStyle.alignItems="flex-start";break;
            }
        }
    }

    const { hide, id: cusId, name, class: cusClass, style: cusStyle, ...cusAttr } = attrs;

    //自定义属性
    let hidechild = "";
    if (colAttrs.hide == 'y' || hide == 'y') {
        // style.display = 'none';
        hidechild = "y";
    }
    rt.otherProps = {};
    rt.cellProps = {};
    rt.otherProps.valign = font.valign;
    if (parseInt(colspan, 0) > 1) {
        rt.otherProps.colspan = colspan;
    }
    if (parseInt(rowspan, 0) > 1) {
        rt.otherProps.rowspan = rowspan;
    }
    rt.otherProps.className = clasnames(colAttrs.class, cusClass);
    rt.otherProps.name = name;
    rt.otherProps.id = cusId;
    for (let key in cusAttr) {
        rt.otherProps[`data-${key.toLowerCase()}`] = cusAttr[key];
    }

    rt.style = { ...borderStyle, ...style, ...camelCaseObject(cusStyle), lineHeight: '1' };
    rt.cellProps.style = { ...innerStyle };
    rt.financial = financial;
    rt.etype = etype;
    rt.evalue = evalue;
    rt.field = field;
    rt.fieldtype = fieldtype;
    rt.detail = detail;
    rt.tab = parseTab(tab);
    rt.stylejson=stylejson;
    rt.getPath = () => {
        return `field${rt.field}`
    }
    rt.format = format;
    rt.mcpoint = cell.mcpoint;
    rt.brsign = cell.brsign;
    rt.jsonparam = cell.jsonparam;
    rt.hidechild = hidechild;
    return rt;
}

const parseTab = (tab: any = {}) => {
    const _tab: TabCellProps = {} as TabCellProps;
    _tab.tabs = [];
    _.each(tab, (v: string, k: string) => {
        if (k == 'areaheight') {
            const [type, height] = v.split(",");
            if (type == '1') {
                _tab.height = 'auto';
            } else {
                _tab.height = height+'px';
            }
        } else if (k == 'defshow') {
            _tab.defaultActiveKey = v;
        } else if (k.startsWith('order_')) {
            const [name, tab] = v.split(',')
            const index = parseInt(k.replace('order_', '')) - 1;
            _.set(_tab.tabs, `${index}`, {
                key: index,
                name,
                tab,
            });
        } else if (k == 'name') {
            _tab.name = v;
        }
    })
    return _tab;
}

/**
 * 单元格样式
 * @param etype
 * @param cell
 */
const appendStyle = (etype: string, cell: any, isMutilContent?: boolean): { style: React.CSSProperties, innerStyle: React.CSSProperties } => {
    const { backgroundColor, field, font = {}, etxtindent } = cell;
    let styleObj = {} as React.CSSProperties;
    let innerStyle = {} as React.CSSProperties;
    if (etype == "7" || etype == "12") {
        return {} as any;
    }
    //背景色
    if (backgroundColor) {
        styleObj.backgroundColor = backgroundColor;
    }
    //背景图片
    if (etype == '6') {
        styleObj.backgroundImage = `url('${field}')`;
        styleObj.backgroundRepeat = "no-repeat";
    }
    //字体
    if (font['text-align']) {
      styleObj.textAlign = font['text-align']
    } else { styleObj.textAlign = 'left' }
    if (font['vertical-align']) { styleObj.verticalAlign = font['vertical-align'] } else { styleObj.verticalAlign = isMutilContent ? 'top' : 'middle' }
    if(font['valign'] ){styleObj.verticalAlign = font['valign'] }
    if (font['bold'] == 'true') { styleObj.fontWeight = 'bold' }
    if (font['font-style'] == 'italic') { styleObj.fontStyle = 'italic' }
    if (font['italic'] == 'true') { styleObj.fontStyle = 'italic' }
    let textDecoration: string[] = [];
    if(font['text-decoration'] == 'underline'){ textDecoration.push('underline')}
    if (font['underline'] == 'true') { textDecoration.push('underline') }
    if (font['deleteline'] == 'true') { textDecoration.push('line-through') }
    styleObj.textDecoration = textDecoration.join(' ');

    let fontSize = parseInt(font['font-size'], 0);
    let fontSizeUnit = "px";  //截取，获取当前字体大小的单位
    if(font['font-size']){
        fontSizeUnit = font['font-size'].slice(-2);
    }
    if (fontSize) {
        styleObj.fontSize = fontSize + fontSizeUnit;
        innerStyle.fontSize = fontSize + fontSizeUnit;
        if (etype == "3" && fontSize > 9) {
            let suitheight = fontsize_compare_height(fontSize);
            styleObj.height = suitheight;
            innerStyle.lineHeight = suitheight + "px";
        }
        // if(etype == "1" && cell.id == "0,0"){ //布局头部字体单位还是用pt先特俗处理下
        //     styleObj.fontSize = fontSize + 'pt';
        //     innerStyle.fontSize = fontSize + 'pt';
        // }
    } else {
        innerStyle.fontSize = '9pt';
    }
    if (font["color"]) { styleObj.color = font["color"] }
    if (font["font-family"]) {
        innerStyle.fontFamily = styleObj.fontFamily = font["font-family"];
    } else {
        innerStyle.fontFamily = "Microsoft YaHei"
    }

    //缩进
    if (etxtindent && etxtindent !== "0") {
        const etxtindent1 = parseFloat(etxtindent) * 8 + "px";
        if (styleObj.textAlign == "left")
            styleObj.paddingLeft = etxtindent1;
        else if (styleObj.textAlign == "right")
            styleObj.paddingRight = etxtindent1;
    }
    innerStyle.wordBreak = "break-all";
    innerStyle.wordWrap = "break-word";

    return { style: styleObj, innerStyle };
}
/**
 * 单元格边框
 * @param eborder
 * @param etype
 */
const appendBorder = (eborder: any, etype: string): React.CSSProperties => {
    let styleObj = {} as React.CSSProperties;
    for (let boder of eborder) {
        const { color, kind, style: borderStyle } = boder;
        if (etype === "7" && (kind === "top" || kind === "bottom")) { //明细所在区域不解析上下边框
            continue;
        }
        let width = 0;
        let style = '';
        if (borderStyle) {
            if (borderStyle == '2') {
                width = 2;
                style = 'solid';
            } else if (borderStyle == '3') {
                width = 1;
                style = 'dashed';
            } else if (borderStyle == '5') {
                width = 3;
                style = 'solid';
            } else if (borderStyle == '6') {
                width = 3;
                style = 'double';
            } else if (borderStyle == '7') {
                width = 1;
                style = 'dotted';
            } else if (borderStyle == '8') {
                width = 2;
                style = 'dashed';
            } else {
                width = 1;
                style = 'solid';
            }
            _.set(styleObj, `border${kind.charAt(0).toUpperCase()}${kind.slice(1)}`, `${width}px ${style} ${color}`);
        }
    }
    return styleObj;
}


const fontsize_compare_height = (fontsize) => {
    if (fontsize <= 10) {
        return 24;
    } else if (fontsize <= 12) {
        return 26;
    } else if (fontsize <= 24) {
        return fontsize * 2;
    } else if (fontsize <= 26) {
        return 50;
    } else if (fontsize <= 28) {
        return 52;
    } else if (fontsize <= 32) {
        return 58;
    } else if (fontsize <= 48) {
        return 82;
    } else {
        return 108;
    }
}
